import tim from 'tim'
import TIM from 'tim-js-sdk'
import store from '..'
import { titleNotify } from '../../utils'
import { apiGroupMember , apiGetHmInfo,apiGetmoreC2cMessage , apiGetmoreGroupMessage } from '@/api/im/api'
const conversationModules = {
  state: {
    currentConversation: {},
    currentMessageList: [],
    nextReqMessageID: '',
    isCompleted: false, // 当前会话消息列表是否已经拉完了所有消息
    conversationList: [],
    servicemsg: {},
    servicemsgList: [],
    servicemsgId: 'C2Cadministrator',
    servicemsgId02: 'C2CdevAdmin',
    converMember: [],  // 当前对话成员信息
    selectedMember: '',
    converList02: {},   //用户会话列表
    atmeMesssage: {},  //艾特我的会话
    nohasim: '',
    weixinsdk: {},
    inputfocus: false, //根据是否有软键盘，控制底部距离
  },
  getters: {
    isIphoneX: state => {
      return /iphone/gi.test(navigator.userAgent) && (screen.height == 812 && screen.width == 375)
    },
    toAccount: state => {
      if (!state.currentConversation || !state.currentConversation.conversationID) {
        return ''
      }
      switch (state.currentConversation.type) {
        case 'C2C':
          return state.currentConversation.conversationID.replace('C2C', '')
        case 'GROUP':
          return state.currentConversation.conversationID.replace('GROUP', '')
        default:
          return state.currentConversation.conversationID
      }
    },
    currentConversationType: state => {
      if (!state.currentConversation || !state.currentConversation.type) {
        return ''
      }
      return state.currentConversation.type
    },
    totalUnreadCount: state => {
      const result = state.conversationList.reduce((count, conversation) => {
        // 当前会话不计算总未读
        if (!store.getters.hidden && state.currentConversation.conversationID === conversation.conversationID) {
          return count
        }
        return count + conversation.unreadCount
      }, 0)
      titleNotify(result)
      return result
    },
    // 用于当前会话的图片预览
    imgUrlList: state => {
      return state.currentMessageList
        .filter(message => message.type === TIM.TYPES.MSG_IMAGE && !message.isRevoked) // 筛选出没有撤回并且类型是图片类型的消息
        .map(message => message.payload.imageInfoArray[0].url)
    }
  },
  mutations: {
    /**
     * 是否有软键盘
     */
    upinputfocus(state,focus){
      state.inputfocus=focus;
    },
    /**
     * 微信sdk-config配置项
     */
    uploadweixinsdk(state,wesdk){
      state.weixinsdk=wesdk;
    },
    /**
     * 是否开通im账号
     */
    uploadNohasim(state,nohasim){
      state.nohasim=nohasim;
    },
    /**
     * 接收消息-增加艾特我的会话
     */
    uploadAtmeMesssage(state,converId){
      state.atmeMesssage[converId]=true;
    },
    /**
     * 切换消息-移除艾特我的会话
     */
    removeAtmeMesssage(state,converId){
      state.atmeMesssage[converId]=false;
    },
    /**
     * 用户会话列表
     * @param {Object} state
     */
    upConverList02(state,converList02) {
      state.converList02 = converList02
    },
    /**
     * 艾特用户
     * @param {Object} state
     */
    uploadSelectedMember(state,selectedMember) {
      state.selectedMember = selectedMember
    },
    /**
     * 更新当前成员信息
     * 调用时机: 切换会话时
     * @param {Object} state
     * @param {list[]} list
     */
    upConverMember(state, list){
      for(let i=0;i<list.length;i++){
        if(list[i].healthManagerType==1){
          list[i].healthManagerTypeName='健康管理师';
        }else if(list[i].healthManagerType==2){
          list[i].healthManagerTypeName='医生';
        }else if(list[i].healthManagerType==3){
          list[i].healthManagerTypeName='营养咨询师';
        }else if(list[i].healthManagerType==4){
          list[i].healthManagerTypeName='心理咨询师';
        }else if(list[i].healthManagerType==5){
          list[i].healthManagerTypeName='身心疗愈师';
        }else if(list[i].healthManagerType==6){
          list[i].healthManagerTypeName='运动医学专家';
        }else if(list[i].healthManagerType==7){
          list[i].healthManagerTypeName='健康督导师';
        }else{
          list[i].healthManagerTypeName='健康管理师';
        }
      }
      state.converMember = list
    },
    /**
     * 更新当前会话
     * 调用时机: 切换会话时
     * @param {Object} state
     * @param {Conversation} conversation
     */
    updateCurrentConversation(state, conversation) {
      state.currentConversation = conversation
      state.currentMessageList = []
      state.nextReqMessageID = ''
      state.isCompleted = false
    },
    /**
     * 更新会话列表
     * 调用时机：触发会话列表更新事件时。CONVERSATION_LIST_UPDATED
     * @param {Object} state
     * @param {Conversation[]} conversationList
     */
    updateConversationList(state, conversationList) {
      try{
        var conver03=JSON.parse(JSON.stringify(state.converList02));
        console.log('conver03>>>>>>>>>>>>>>>>:'+conver03.length)
        console.log(conver03)
        
        for(let i=0;i<conversationList.length;i++){
          if(conver03[conversationList[i].conversationID]){
            conver03[conversationList[i].conversationID].isConver=true
          }
        }
   
        for(let j in conver03){
          // if(!conver03[j].isConver&&(conver03[j].serviceStatus==1)){
          // if(!conver03[j].isConver&&(conver03[j].serviceStatus==1 || conver03[j].serviceStatus==2)){
          if(!conver03[j].isConver&&(conver03[j].serviceStatus==1 || conver03[j].serviceStatus==2)){
            if( conver03[j].serviceStatus==1){
              conversationList.push({
                conversationID: j,
                type: j.indexOf('C2C')==0?'C2C':'GROUP',
                unreadCount: 0,
                lastMessage: {
                  fromAccount: 0,
                  isRevoked: false,
                  lastSequence: 0,
                  lastTime: 0,
                  messageForShow: "",
                  payload: null,
                  type: ""
                },
                groupProfile: {
                  avatar: conver03[j].campGroupFaceUrl||'',
                  groupID: conver03[j].campGroupImName,
                  introduction: "",
                  lastInfoTime: conver03[j].createTime,
                  lastMessage: {},
                  muteAllMembers: false,
                  name: conver03[j].campGroupName,
                  notification: "",
                  selfInfo: {},
                  type: "Public"
                },
                userProfile: {
                  avatar: conver03[j].mgrFaceUrl||'',
                  nick: conver03[j].mgrNickname||'',
                  userID: conver03[j].healthManagerImAccount||''
                }
              })
            }else if(conver03[j].serviceStatus==2){
              if(j.indexOf('C2C') == 0){

                var params = {
                  userImAccount: localStorage.getItem('userID'),
                  hgrImAccount: 'hm_'+conver03[j].healthManagerId,
                  maxCnt: 1
                }

                apiGetmoreC2cMessage(params).then(res => {
                  if(res.status == 200){
                    if(res.data.length){
                      conversationList.push({
                        conversationID: j,
                        type: j.indexOf('C2C')==0?'C2C':'GROUP',
                        unreadCount: 0,
                        lastMessage: {
                          fromAccount: 0,
                          isRevoked: false,
                          lastSequence: 0,
                          lastTime: res.data[0].time,
                          messageForShow:  res.data[0].payload.text|| res.data[0].payload.Text,
                          payload: res.data[0].payload,
                          type: ""
                        },
                        groupProfile: {
                          avatar: conver03[j].campGroupFaceUrl||'',
                          groupID: conver03[j].campGroupImName,
                          introduction: "",
                          lastInfoTime: conver03[j].createTime,
                          lastMessage: {},
                          muteAllMembers: false,
                          name: conver03[j].campGroupName,
                          notification: "",
                          selfInfo: {},
                          type: "Public"
                        },
                        userProfile: {
                          avatar: conver03[j].mgrFaceUrl||'',
                          nick: conver03[j].mgrNickname||'',
                          userID: conver03[j].healthManagerImAccount||''
                        }
                      })
                       
                    }
                    
                  } 
                })


              }else {
                var params = {
                  // userImAccount: localStorage.getItem('userID'),
                  // hgrImAccount: 'hm_'+conver03[j].healthManagerId,
                  campGroupId: 'xtGroup_'+conver03[j].campGroupId,
                  // campGroupId: 'xtGroup_30649',
                  maxCnt: 1,
                }
 
                apiGetmoreGroupMessage(params).then(res => {
                  if(res.status == 200){
                    if(res.data.length){
                      conversationList.push({
                        conversationID: j,
                        type: j.indexOf('C2C')==0?'C2C':'GROUP',
                        unreadCount: 0,
                        lastMessage: {
                          fromAccount: 0,
                          isRevoked: false,
                          lastSequence: 0,
                          lastTime: res.data[0].time,
                          messageForShow: res.data[0].payload.text|| res.data[0].payload.Text,
                          payload: res.data[0].payload,
                          type: ""
                        },
                        groupProfile: {
                          avatar: conver03[j].campGroupFaceUrl||'',
                          groupID: conver03[j].campGroupImName,
                          introduction: "",
                          lastInfoTime: conver03[j].createTime,
                          lastMessage: {},
                          muteAllMembers: false,
                          name: conver03[j].campGroupName,
                          notification: "",
                          selfInfo: {},
                          type: "Public"
                        },
                        userProfile: {
                          avatar: conver03[j].mgrFaceUrl||'',
                          nick: conver03[j].mgrNickname||'',
                          userID: conver03[j].healthManagerImAccount||''
                        }
                      })
                    }else{
                      //不存在数据
                      conversationList.push({
                        conversationID: j,
                        type: j.indexOf('C2C')==0?'C2C':'GROUP',
                        unreadCount: 0,
                        lastMessage: {
                          fromAccount: 0,
                          isRevoked: false,
                          lastSequence: 0,
                          lastTime: 0,
                          messageForShow: '',
                          payload: '',
                          type: ""
                        },
                        groupProfile: {
                          avatar: conver03[j].campGroupFaceUrl||'',
                          groupID: conver03[j].campGroupImName,
                          introduction: "",
                          lastInfoTime: 0,
                          lastMessage: {},
                          muteAllMembers: false,
                          name: conver03[j].campGroupName,
                          notification: "",
                          selfInfo: {},
                          type: "Public"
                        },
                        userProfile: {
                          avatar: conver03[j].mgrFaceUrl||'',
                          nick: conver03[j].mgrNickname||'',
                          userID: conver03[j].healthManagerImAccount||''
                        }
                      })
                    }
                  } 
                })

              }
            }
            
          }
        }
        console.log('conversationList------------')
        console.log(conversationList)

      }catch(e){console.log(e)}
      state.conversationList = conversationList
    },
    /**
     * 重置当前会话
     * 调用时机：需要重置当前会话时，例如：当前会话是一个群组，正好被踢出群时（被踢群事件触发），重置当前会话
     * @param {Object} state
     */
    resetCurrentConversation(state) {
      state.currentConversation = {}
    },
    /**
     * 将消息插入当前会话列表
     * 调用时机：收/发消息事件触发时
     * @param {Object} state
     * @param {Message[]|Message} data
     * @returns
     */
    pushCurrentMessageList(state, data) {
      // 还没当前会话，则跳过
      if (!state.currentConversation.conversationID) {
        return
      }
      if (Array.isArray(data)) {
        // 筛选出当前会话的消息
        const result = data.filter(item => item.conversationID === state.currentConversation.conversationID)
        state.currentMessageList = [...state.currentMessageList, ...result]
      } else if (data.conversationID === state.currentConversation.conversationID) {
        state.currentMessageList = [...state.currentMessageList, data]
      }
    },
    /**
     * 从当前消息列表中删除某条消息
     * @param {Object} state
     * @param {Message} message
     */
    removeMessage(state, message) {
      const index = state.currentMessageList.findIndex(({ ID }) => ID === message.ID)
      if (index >= 0) {
        state.currentMessageList.splice(index, 1)
      }
    },
    reset(state) {
      Object.assign(state, {
        currentConversation: {},
        currentMessageList: [],
        nextReqMessageID: '',
        isCompleted: false, // 当前会话消息列表是否已经拉完了所有消息
        conversationList: []
      })
    },
    /**
     * 服务通知消息
     * qisibo
     * @param {Object} state
     * @param {Message} message
     */
    updateServicemsg(state, servicemsg) {
      if(servicemsg.conversationID){
        state.servicemsg = servicemsg
      }
    },
    getServicemsg(state, servicemsgList) {
      state.servicemsgList = servicemsgList
    },
    addSeviceMessageList(state, seviceMessageList) {
      const { currentMessageList } = state
      state.currentMessageList = [...seviceMessageList, ...currentMessageList]
    }
  },
  actions: {
    /**
     * 获取当前成员信息
     * 调用时机: 切换会话时
     * @param {Object} context
     * @param {conversationID} conversationID
     */
    getConverMember(context, conversationID){
      if (context.state.currentConversation.type === TIM.TYPES.CONV_GROUP) {
        apiGroupMember({
          campGroupId: conversationID.split('_')[1],
          identityType: 2,
          allDataFlag: true,
          profile_id: localStorage.getItem('profileId'),
          token: localStorage.getItem('token')
        }).then(res => {
          if(res.status == 200){
            context.commit('upConverMember', res.data)
          }else{
            context.commit('upConverMember', [])
          }
        })
      }else if(context.state.currentConversation.type === TIM.TYPES.CONV_C2C){
        apiGetHmInfo({
          middleId: conversationID.split('_')[1]
        }).then(res => {
          if(res.status == 200){
            res.data.allowPrivateChat=false
            context.commit('upConverMember', [res.data])
          }else{
            context.commit('upConverMember', [])
          }
        })
      }else{
        context.commit('upConverMember', [])
      }
      // context.commit('upConverMember', data)
    },
    /**
     * 获取消息列表
     * 调用时机：打开某一会话时或下拉获取历史消息时
     * @param {Object} context
     * @param {String} conversationID
     */
    getMessageList(context, conversationID) {
      if (context.state.isCompleted) {
        context.commit('showMessage', {
          message: '已经没有更多的历史消息了哦',
          type: 'info'
        })
        return
      }
      if(!conversationID){
        return;
      }
      const { nextReqMessageID, currentMessageList } = context.state
      tim.getMessageList({ conversationID, nextReqMessageID, count: 15 }).then(imReponse => {
        // 更新messageID，续拉时要用到
        context.state.nextReqMessageID = imReponse.data.nextReqMessageID
        context.state.isCompleted = imReponse.data.isCompleted
        // 更新当前消息列表，从头部插入
        context.state.currentMessageList = [...imReponse.data.messageList, ...currentMessageList]
      })
    },
    /**
     * 切换会话
     * 调用时机：切换会话时
     * @param {Object} context
     * @param {String} conversationID
     */
    checkoutConversation(context, conversationID) {
      context.commit('resetCurrentMemberList')
      // 1.切换会话前，将切换前的会话进行已读上报
      if (context.state.currentConversation.conversationID) {
        const prevConversationID = context.state.currentConversation.conversationID
        tim.setMessageRead({ conversationID: prevConversationID })
      }
      tim.setMessageRead({ conversationID })
      // 2.待切换的会话也进行已读上报
      if(!conversationID){
        return ;
      }
      // 3. 获取会话信息
      return tim.getConversationProfile(conversationID).then(({ data }) => {
        
        console.log('获取会话信息获取会话信息')
        console.log(data)
        // 3.1 更新当前会话
       context.commit('updateCurrentConversation', data.conversation)
        // 3.2 获取消息列表
        context.dispatch('getMessageList', conversationID)
        // 接口获取当前会话成员信息
        context.dispatch('getConverMember', conversationID )
        // 3.3 拉取第一页群成员列表
        if (data.conversation.type === TIM.TYPES.CONV_GROUP) {
          return context.dispatch('getGroupMemberList', data.conversation.groupProfile.groupID)
        }
        //  wx.miniProgram.navigator({url:'/im/chat'})
        // console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
        // console.log(context.state.conversationList)

        return Promise.resolve()
 
      })
    },
    /**
     * 打开服务列表
     * 获取列表信息，上报已读
     * @param {Object} context
     * @param {String} conversationID
     */
    getServicemsgList(context, conversationID) {
      // 已读上报
      tim.setMessageRead({ conversationID: conversationID })
    },
  }
}

export default conversationModules
